<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <!-- 引入 Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- 引入 Font Awesome 图标库 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link href="./css/style.css" rel="stylesheet">
</head>
<body class="flex items-center justify-center min-h-screen">

<div class="card bg-white p-8 rounded-lg shadow-md w-full max-w-md space-y-4">
    <h1 class="text-2xl font-bold text-center mb-4">登录</h1>

    <!-- 登录表单 -->
    <form id="login-form" class="space-y-4">
        <div>
            <label for="email" class="block text-sm font-medium text-gray-700">邮箱</label>
            <input type="email" id="email" name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <div class="error mt-1 text-red-500 text-sm hidden">请输入有效的邮箱地址</div>
        </div>
        <div>
            <label for="password" class="block text-sm font-medium text-gray-700">密码</label>
            <input type="password" id="password" name="password" required pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <div class="error mt-1 text-red-500 text-sm hidden">密码至少包含一个字母和一个数字，且长度不少于8个字符，支持 - 和 _ 符号</div>
        </div>
        <div>
            <label for="captcha" class="block text-sm font-medium text-gray-700">验证码</label>
            <div class="flex items-center space-x-4">
                <img id="captcha-image" src="/api/generate-captcha" alt="Captcha" class="border border-gray-300 rounded-md flex-shrink-0 h-10 w-32">
                <button id="refresh-captcha-button" type="button" class="inline-flex items-center px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:shadow-outline">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m9.818 9H13m-4.582-.122c-.724 1.892-1.635 3.19-2.98 4.109a60.482 60.482 0 01-10.693-3.145 59.466 59.466 0 01-4.462-10.703 60.003 60.003 0 0111.057-6.55M12 12v4.5m5.5-19.5l-1.5 1.5L12 9l-3 3 1.5 1.5m-6-3H6m6 0h6M6 18h6m6-6h-6"/>
                    </svg>
                    刷新
                </button>
            </div>
            <input type="text" id="captcha" name="captcha" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <div class="error mt-1 text-red-500 text-sm hidden">请输入正确的计算结果</div>
        </div>
        <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline inline-flex items-center justify-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"/>
            </svg>
            登录
        </button>
    </form>

    <!-- 注册跳转链接 -->
    <div class="text-center mt-4">
        <p class="text-sm text-gray-600">还没有账号？ <a href="register_verify.html" class="text-indigo-600 hover:text-indigo-700">立即注册</a></p>
    </div>
</div>

<!-- 引入 jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    $(document).ready(function () {
        console.log("jQuery is loaded and ready!");
    
        // 刷新验证码函数
        function refreshCaptcha() {
            console.log("Refreshing captcha...");
            const captchaImage = document.getElementById('captcha-image');
            captchaImage.src = '/api/generate-captcha?' + new Date().getTime();
        }
    
        // 绑定刷新验证码按钮的点击事件
        document.getElementById('refresh-captcha-button').addEventListener('click', refreshCaptcha);
    
        // 监听输入框的 blur 事件
        $('#email').on('blur', function () {
            validateField($(this), validateEmail);
        });
    
        $('#password').on('blur', function () {
            validateField($(this), validatePassword);
        });
    
        $('#captcha').on('blur', function () {
            validateField($(this), validateCaptcha);
        });
    
        // 提交表单时验证所有字段
        $('#login-form').on('submit', function (e) {
            e.preventDefault();
    
            const email = $('#email').val();
            const password = $('#password').val();
            const captcha = $('#captcha').val();
    
            let isValid = true;
    
            // 验证邮箱格式
            if (!validateEmail(email)) {
                showValidationError($('#email'));
                isValid = false;
            } else {
                hideValidationError($('#email'));
            }
    
            // 验证密码格式
            if (!validatePassword(password)) {
                showValidationError($('#password'));
                isValid = false;
            } else {
                hideValidationError($('#password'));
            }
    
            // 验证验证码格式
            if (!validateCaptcha(captcha)) {
                showValidationError($('#captcha'));
                isValid = false;
            } else {
                hideValidationError($('#captcha'));
            }
    
            // 如果所有字段都有效，则发送请求到服务器
            if (isValid) {
                $.ajax({
                    url: '/api/login',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ email, password, captcha }),
                    success: function (response) {
                        sessionStorage.setItem('isLoggedIn', 'true');
                        sessionStorage.setItem('userEmail', email);
                        sessionStorage.setItem('userId', response.id); // 存储 userId
                        alert('登录成功');
                        window.location.href = 'profile.html'; // 跳转到个人中心
                    },
                    error: function (xhr) {
                        const errorMessage = xhr.responseJSON ? xhr.responseJSON.message : "邮箱、密码或验证码错误，请重试";
                        alert(errorMessage);
                        refreshCaptcha(); // 刷新验证码
                    }
                });
            }
        });
    
        // 显示验证错误
        function showValidationError($input) {
            const $errorDiv = $input.next('.error');
            $errorDiv.removeClass('hidden');
        }
    
        // 隐藏验证错误
        function hideValidationError($input) {
            const $errorDiv = $input.next('.error');
            $errorDiv.addClass('hidden');
        }
    
        // 验证字段通用函数
        function validateField($input, validationFunction) {
            const value = $input.val();
            if (!validationFunction(value)) {
                showValidationError($input);
            } else {
                hideValidationError($input);
            }
        }
    
        // 验证邮箱格式
        function validateEmail(email) {
            const emailPattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
            return emailPattern.test(email);
        }
    
        // 验证密码格式
        function validatePassword(password) {
            const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}$/;
            return passwordPattern.test(password);
        }
    
        // 验证验证码格式
        function validateCaptcha(captcha) {
            const captchaPattern = /^\d+$/; // 假设验证码是数字
            return captchaPattern.test(captcha);
        }
    });
</script>

</body>
</html>